<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class ConfigController extends Controller
{
    //显示网站管理列表
    public function index()
    {
    	$title = '网站管理';
    	$data = DB::table('config') -> first();
    	// dd($data);
    	return view('admin.config.index',['data' => $data,'title' => $title]);
    }

    // 更新
    public function update(Request $request)
    {
    	$data = $request -> except('_token','oldlogo','id');
    	//获取id
    	$id = $request -> input('id');

    	//限制判断
    	$this -> validate($request, [
    			         'webname' => 'required',
    			            'copy' => 'required',
    		],[
    			'webname.required' => '网站名不能为空',
    			   'copy.required' => '版权不能为空',

    		]);
    	 //获取老图片地址
        $oldpath = '.'.$request -> input('oldlogo');
        // dd($oldpath);
        //处理logo
        if($request -> hasFile('logo'))
        {
            if($request -> file('logo') -> isValid())
            {
                //获取后缀名
                $suffix = $request -> file('logo') -> getClientOriginalExtension();
                // echo $suffix;
                //随机文件名
                $fileName = time().mt_rand(100000,999999).'.'.$suffix;
                // $path = date('Ymd');
                $path = './uploads';
                $request -> file('logo') -> move($path,$fileName);

                $data['logo'] = trim($path.'/'.$fileName,'.');
                // dd($data);
               
                if(file_exists($oldpath))
                {
                    unlink($oldpath);
                }
                
            }
        }

        //处理switch值
        if($data['switch'] == '开')
        {
            $data['switch'] = 1;
        }else
        {
            $data['switch'] = 2;
        }

        //处理status值
        if($data['status'] == '开')
        {
            $data['status'] = 1;
        }else
        {
            $data['status'] = 2;
        }

        //执行添加数据
        $res = DB::table('config') -> where('id',$id) -> update($data);
      
        //判断
        if($res)
        {
            return redirect('/admin/config/index') -> with(['success' => '更新成功']);
        }else
        {
            return back() -> with(['error' => '更新失败']);
        }
    }
}
